package com.estar.app.business.mobileLogin.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class ObjCopyUtils {
	private static final Logger logger = Logger.getLogger(ObjCopyUtils.class);
	public static Object beansCopy(Object fromObj,Object toObj){
		try {		
			Field[] fields = fromObj.getClass().getDeclaredFields();
			Field[] toObjFields = toObj.getClass().getDeclaredFields();
			List<String> nameList = new ArrayList<String>();
			
			for (int i = 0; i < toObjFields.length; i++) {
				nameList.add(toObjFields[i].getName());
			}
			
			for (int i = 0; i < fields.length; i++) {
				String name = fields[i].getName();
				if(!nameList.contains(name))
					continue;
				
				Field fromField = fromObj.getClass().getDeclaredField(name);
				Object obj = fromField.get(fromObj);
				if(""!=obj && null!=obj){
					Field field = toObj.getClass().getDeclaredField(name);
					field.set(toObj, fields[i].get(fromObj));
				}
				//Field field = toObj.getClass().getDeclaredField(name);
				//Object obj = field.get(toObj);
				
				//if(""==obj || null==obj)
				//field.set(toObj, fields[i].get(fromObj));
			}
		} catch (Exception e) {
			logger.error("系统异常：",e);
		}
		return toObj;
	}
	
	
	public static Object beansCopyForUpdate(Object fromObj,Object toObj){
		try {		
			Field[] fields = fromObj.getClass().getDeclaredFields();
			Field[] toObjFields = toObj.getClass().getDeclaredFields();
			List<String> nameList = new ArrayList<String>();
			
			for (int i = 0; i < toObjFields.length; i++) {
				nameList.add(toObjFields[i].getName());
			}
			
			for (int i = 0; i < fields.length; i++) {
				String name = fields[i].getName();
				if(!nameList.contains(name))
					continue;
				
				Field field = toObj.getClass().getDeclaredField(name);
				
				field.set(toObj, fields[i].get(fromObj));
			}
		} catch (Exception e) {
			logger.error("系统异常：",e);
		}
		return toObj;
	}
	
	public static Object beansCopyFromJDBC(Object fromObj,Object toObj){
		try {		
			Field[] fields = fromObj.getClass().getDeclaredFields();
			Field[] toObjFields = toObj.getClass().getDeclaredFields();
			
			List<String> fromNameList = new ArrayList<String>();
			List<String> toNameList = new ArrayList<String>();
			
			
			for (int i = 0; i < fields.length; i++) {
				fromNameList.add(fields[i].getName());
			}
			for (int i = 0; i < toObjFields.length; i++) {
				toNameList.add(toObjFields[i].getName());
			}
			
			for (int i = 0; i < fields.length; i++) {
				String name = fields[i].getName();
				if(!toNameList.contains(name)){
					continue;
				}else{
				
					Field field = toObj.getClass().getDeclaredField(name);
				
					field.set(toObj, fields[i].get(fromObj));
				}
			}
		} catch (Exception e) {
			logger.error("系统异常：",e);
		}
		return toObj;
	}
}
